package com.ruoyi.operation.order.data.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.operation.order.data.domain.Allotment;
import com.ruoyi.operation.order.data.domain.OrderData;
import com.ruoyi.operation.order.data.mapper.IOrderDataMapper;
import com.ruoyi.operation.order.data.service.IOrderDataService;
import com.ruoyi.operation.order.product.domain.Product;
import com.ruoyi.operation.order.product.mapper.IProductMapper;
import com.ruoyi.operation.order.util.ExportExcelUtil;
import com.ruoyi.operation.order.wwebchat.domain.Wwebchat;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author wangzhiwei phone(WeChat)):15062775766
 * @date 2020/5/2 21:24
 */
@Service
public class IOrderDataServiceImpl implements IOrderDataService {

    @Autowired
    IOrderDataMapper iOrderDataMapper;

    @Autowired
    IProductMapper iProductMapper;

    /**
     * 录入客户管数据
     * @param orderData
     * @return
     */
    @Override
    public int saveOrderData(OrderData orderData) {
        return iOrderDataMapper.saveOrderData(orderData);
    }

    /**
     *  导入数据
     * @param orderDataList
     * @return
     */
    @Override
    public String importOrderDate(List<OrderData> orderDataList ) {
        if (StringUtils.isNull(orderDataList) || orderDataList.size() == 0)
        {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (OrderData orderData : orderDataList)
        {
            try
            {
                // 验证旺旺号存在
//                List<EnterForm> enterFormList1=iEnterFormMapper.allListEnter(enterForm.getWwNum());
//                if (StringUtils.isNull(enterFormList1))
//                {
////                    enterForm.setUpdateDate();
//                    enterForm.setCreateBy(ShiroUtils.getLoginId());
//                    Dept dept= deptService.selectByDeptName(enterForm.getDeptName());
//                    enterForm.setEnterDeptId(dept.getDeptId().toString());
//                    enterForm.setFormNature("3");
//                    this.saveEnterForm(enterForm);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、订单 " + enterForm.getFormNum() + " 导入成功");
//                }
//                else
//                {
                orderData.setCreateBy(ShiroUtils.getLoginId());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                orderData.setEnterDate(simpleDateFormat.format(new Date()));
                this.saveOrderData(orderData);
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、客户 " + orderData.getCustomerName() + " 导入成功");
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " +  orderData.getCustomerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导入客客户书记信息
     * @param file
     * @throws Exception
     */
    @Override
    public void importExcel(MultipartFile file) throws Exception {
        // 获取当前登录人的user对象
        // 获取文件上传时的文件名
        String fileName = file.getOriginalFilename();
       /* //正则验证上传文件时的格式
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return baseDto;
        }*/
        try {
            //当上传的文件是excel2003
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            // 查询所有的业务员的信息
            List<OrderData> orderDataList = iOrderDataMapper.allList();
            //通过InputStream读取和写入文件
            InputStream is = file.getInputStream();
            Workbook web = null;
            if (isExcel2003) {
                web = new HSSFWorkbook(is);
            } else {
                web = new XSSFWorkbook(is);
            }
            //获取第一个Excel表格
            Sheet sheet = web.getSheetAt(0);
            // 定义一个新的list集合
            List<OrderData> list = new ArrayList<>();
            List<OrderData> newList = new ArrayList<>();

            // 查询所有的商品名称
            // 查询所有的业务员的信息
            if (sheet != null) {
                // 定义一个对象
                OrderData orderData;
                for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    orderData = new OrderData();
                    // 客户姓名
                    if (row.getCell(0) != null) {
                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                        orderData.setCustomerName(row.getCell(0).getStringCellValue());
                    }else {
                        break;
                    }
                    // 旺旺号
                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        String getWangWangNumber = row.getCell(1).getStringCellValue();
                        // for循环list集合
                        for (OrderData dataBean : orderDataList){
                            if (!dataBean.getWangwangNumber().equals(getWangWangNumber)){
                                orderData.setWangwangNumber(getWangWangNumber);
                                break;
                            }else {
                                continue;
                            }
                        }
                        break;
                    }
                    // 产品名称
                    if (row.getCell(2) != null) {
                        row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                        orderData.setProductName(row.getCell(2).getStringCellValue());

                    }
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                        String linkPhone = row.getCell(3).getStringCellValue();
                        orderData.setCustomerPhone(linkPhone);
                    }

                    if (row.getCell(4) != null) {
                        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                        orderData.setCustomerAddress(row.getCell(4).getStringCellValue());
                    }


                    orderData.setCreateBy(ShiroUtils.getLoginId());
                    orderData.setIsOpen(0);
                    orderData.setContactsNumber(0);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    orderData.setEnterDate(simpleDateFormat.format(new Date()));
                    orderData.setLinkStatus(0);
                    list.add(orderData);
                }
                if (orderDataList.size() > 0){
                    for (OrderData bean : list) {
                        boolean flag = true;
                        for (OrderData newBean : orderDataList) {
                            if (newBean.getWangwangNumber().equals(bean.getWangwangNumber()) || newBean.getCustomerPhone().equals(bean.getCustomerPhone())) {
                                flag = false;
                                break;
                            }
                        }
                        if (flag) {
                            newList.add(bean);
                        }
                    }
                    // 循环添加
                    if (newList.size() > 0){
                        iOrderDataMapper.importExcel(newList);
                    }else {
                        iOrderDataMapper.importExcel(list);
                    }

                }else {
                    iOrderDataMapper.importExcel(list);
                }


            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 分页查询所有的数据
     * @param orderData
     * @return
     */
    @Override
    public List<OrderData> findAll(OrderData orderData) {
        return iOrderDataMapper.findAll(orderData);
    }

    /**
     * 导出Excel表格
     * @param orderData
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    public void exportExcel(OrderData orderData, HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<OrderData> orderDataList = iOrderDataMapper.exportExcel(orderData);
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建导的Excel表的名字
        //sheet名
        HSSFSheet sheet = workbook.createSheet("客户数据表");
        // 设置导出文件的名字和导出的格式
        String fileName = "客户数据表"+".xls";
        String agent = request.getHeader("USER-AGENT");
        if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)
        {
            fileName = "=?UTF-8?B?" + (new String(Base64Utils.encodeToString(fileName.getBytes("UTF-8")))) + "?=";
        } else {
            fileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 新增数据行，设置单元格数据
        int rowNum  = 1;
        // 定义导出Excel的表格
        String[] title = {"姓名","旺旺号","产品名称","联系方式","地址","导入时间"};
        String[] colList = {"customerName","wangwangNumber","productName","customerPhone","customerAddress","enterDate"};
        HSSFRow row = sheet.createRow(0);
        // 在Excel表中添加表头
        for (int i = 0;i<title.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(title[i]);
            cell.setCellValue(text);
        }
        // 在表中存放查询到的数据到对应的列
        for (OrderData c: orderDataList){
            HSSFRow row1 = sheet.createRow(rowNum);
            int j = 0;
            for(String s:colList){
                try {
                    row1.createCell(j).setCellValue((String)getGetMethod(c, s));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                j++;
            }
            rowNum++;
        }
        ExportExcelUtil.outPut(response,workbook,fileName);
    }

    /**
     * 根据属性，获取get方法
     * @param ob 对象
     * @param name 属性名
     * @return
     * @throws Exception
     */
    private Object getGetMethod(Object ob , String name)throws Exception{
        Method[] m = ob.getClass().getMethods();
        for(int i = 0;i < m.length;i++){
            if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
                return m[i].invoke(ob);
            }
        }
        return null;
    }

    @Override
    public int countWwNum(String wangwangNumber) {
        return iOrderDataMapper.countWwNum(wangwangNumber);
    }

    /**
     * 批量删除客户信息
     * @param dataIds 需要删除的数据ID
     * @return
     * @throws Exception
     */
    @Override
    public int batchDeleteIds(String dataIds) throws Exception {
        String[] dataIdss = Convert.toStrArray(dataIds);
        return iOrderDataMapper.batchDeleteIds(dataIdss);
    }

    /**
     * 导入可客户数据
     * @param orderDataList
     * @param isUpdateSupport
     * @return
     */
    @Override
    public String importOrderData(List<OrderData> orderDataList ,Boolean isUpdateSupport) {
        if (StringUtils.isNull(orderDataList) || orderDataList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        orderDataList.remove(null);
//        String operName = ShiroUtils.getLoginName();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (OrderData orderData : orderDataList)
        {
            try
            {

                // 验证旺旺号是否存在
                // 验证旺旺号存在
                List<OrderData> wwList = iOrderDataMapper.checkWangWangNumber(orderData.getWangwangNumber());
                List<OrderData> phoneList = iOrderDataMapper.checkLinkPhone(orderData.getCustomerPhone());
//                User u = userMapper.selectUserByLoginName(user.getLoginName());
                if (wwList.size() == 0 && phoneList.size() == 0)
                {
                    orderData.setCreateBy(ShiroUtils.getLoginId());
                    orderData.setIsOpen(0);
                    orderData.setContactsNumber(0);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    orderData.setEnterDate(simpleDateFormat.format(new Date()));
                    SimpleDateFormat dateMin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    orderData.setExportDate(dateMin.format(new Date()));
                    orderData.setLinkStatus(0);
                    orderData.setIsAssignment(0);
                    this.saveOrderData(orderData);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + orderData.getCustomerName() + " 导入成功");
                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、订单 " + orderData.getCustomerName() + " 已存在");
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单 " + orderData.getCustomerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
//        if (failureNum > 0)
//        {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new BusinessException(failureMsg.toString());
//        }
//        else
//        {
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
        return successMsg.toString();
    }

    /**
     * 查询所有的未分配的客户的数据
     * @return
     */
    @Override
    public String getDataCount() {
        return iOrderDataMapper.getDataCount();
    }

    /**
     * 根据前台传来的分配的人数查询对应的需要分配的条数
     * @param allotment
     * @return
     */
    @Override
    public List<String> getAllId(Allotment allotment) {
        return iOrderDataMapper.getAllId(allotment);
    }

    @Override
    public int batchUpdate(OrderData orderData) {
        return iOrderDataMapper.batchUpdate(orderData);
    }

    @Override
    public String yetCount(Long userId) {
        return iOrderDataMapper.yetCount(userId);
    }
}
